package com.hkts.flow.manager.api;


import com.dragon.tools.common.ReturnCode;
import com.dragon.tools.pager.PagerModel;
import com.dragon.tools.pager.Query;
import com.dragon.tools.vo.ReturnVo;
import com.hkts.flow.api.flowable.*;

import com.hkts.flow.api.flowable.ret.FormInfoVo;
import com.hkts.flow.api.flowable.ret.ProcessInstanceVo;
import com.hkts.flow.api.flowable.ret.TaskVo;
import com.hkts.flow.api.modelleave.Leave;
import com.hkts.flow.api.performanceVo.PerformanceInfoNameAndUserNickVo;
import com.hkts.flow.api.performanceVo.ProcessNodeNameAndProcessInstanceIdVo;
import com.hkts.flow.api.performanceVo.TaskAndAssessmentInfoVo;
import com.hkts.flow.core.service.flowable.IFlowableProcessInstanceService;
import com.hkts.flow.core.service.flowable.IFlowableTaskService;
import com.hkts.flow.core.service.leave.ILeaveService;

import com.hkts.flow.feign.FeignInterface;
import com.hkts.flow.feign.FeignPerformance;
import com.hkts.flow.manager.utils.Result;
import com.hkts.flow.manager.utils.ResultUtil;
import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;

import org.flowable.task.api.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : bruce.liu
 * @title: : ApiFlowableTaskResource
 * @projectName : flowable
 * @description: 任务列表
 * @date : 2019/11/2115:34
 */
@RestController
@RequestMapping("/rest/task")
public class ApiFlowableTaskResource extends BaseResource {

    @Autowired
    private IFlowableTaskService flowableTaskService;
    @Autowired
    private IFlowableProcessInstanceService flowableProcessInstanceService;
    @Autowired
    private ILeaveService leaveService;
    @Autowired
    private HistoryService historyService;

    @Autowired
    private FeignInterface feignInterface;
    @Autowired
    private FeignPerformance feignPerformance;
    /**
     * 获取待办任务列表
     *
     * @param params 参数
     * @param query  查询条件
     * @return
     */
    @GetMapping(value = "/get-applying-tasks")
    public PagerModel<TaskVo> getApplyingTasks(TaskQueryVo params, Query query) {

        params.setUserCode(this.getLoginUser().getId());

        PagerModel<TaskVo> pm = flowableTaskService.getApplyingTasks(params, query);
        return pm;
    }
    //被完成任务后远程调用自动跳转得待办
    @GetMapping(value = "/getPerPormanceByPerPormance")
    public String  getPerPormanceByPerPormance() {
        TaskQueryVo params=new TaskQueryVo();
        Query query=new Query();
        query.setPageNum(0);
        Map<String,Object> map=new HashMap<>();
        List<String> departmentIds = feignInterface.getDepartmentIds();
      /*  if(departmentIds.size()==0){
            map.put("code","500");
            map.put("msg","当前用户无数据权限！");
            return map;
        }*/
        params.setUserOrgCodes(departmentIds);
        params.setUserCode(this.getLoginUser().getId());
        PagerModel<TaskVo> pm = flowableTaskService.getPerformanceApplyingTasks(params, query);
        List<String> pIdList=new ArrayList<String>();
        pm.getData().stream().forEach(taskVo -> {
            pIdList.add(taskVo.getProcessInstanceId());
        });

       if(pm.getData().size()>0){
           map.put("processInstanceId",pm.getData().get(0).getProcessInstanceId());
           map.put("taskId",pm.getData().get(0).getTaskId());
           map.put("code","200");
           return pm.getData().get(0).getProcessInstanceId()+","+pm.getData().get(0).getTaskId();
       }
        map.put("code","500");
        map.put("msg","无下一条记录");
        return "500";
    }

    /**
     * 获取待办任务列表
     *
     * @param params 参数
     * @param query  查询条件
     * @return
     */
    @GetMapping(value = "/get-performance-applying-tasks")
    public Result  getPerPormanceApplyingTasks(TaskQueryVo params, Query query) {
        List<String> departmentIds = feignInterface.getDepartmentIds();
        if(departmentIds.size()==0){
            return ResultUtil.data(null);
        }
        params.setUserOrgCodes(departmentIds);
        params.setUserCode(this.getLoginUser().getId());

        PagerModel<TaskVo> pm = flowableTaskService.getPerformanceApplyingTasks(params, query);
        List<String> pIdList=new ArrayList<String>();
        pm.getData().stream().forEach(taskVo -> {
            pIdList.add(taskVo.getProcessInstanceId());
        });
       List<HkAssessmentInfoVo> hkAssessmentInfoByProIds = feignPerformance.getHkAssessmentInfoByProIds(pIdList);
       List<String> performanceList=new ArrayList<String>();
       List<TaskAndAssessmentInfoVo>  taskAndAssessmentInfoVo=new ArrayList<>();
            pm.getData().stream().forEach(taskVo -> {
                for(int i=0;i<hkAssessmentInfoByProIds.size();i++){
                    if(hkAssessmentInfoByProIds.get(i).getProcessInstanceId().equals(taskVo.getProcessInstanceId())){
                        TaskAndAssessmentInfoVo vo=new TaskAndAssessmentInfoVo();
                        vo.setTaskVo(taskVo);
                        vo.setAssessmentInfoVo(hkAssessmentInfoByProIds.get(i));
                        performanceList.add(taskVo.getProcessInstanceId());
                        taskAndAssessmentInfoVo.add(vo);
                        break;
                    }
                }
            });
       for(int i=0;i<pm.getData().size();i++){
           if(!performanceList.contains(pm.getData().get(i).getProcessInstanceId())){
               TaskAndAssessmentInfoVo vo=new TaskAndAssessmentInfoVo();
               vo.setTaskVo(pm.getData().get(i));
               taskAndAssessmentInfoVo.add(vo);
           }
       }
        PagerModel<TaskAndAssessmentInfoVo> pp=new PagerModel();
        pp.setTotal(pm.getTotal());
        pp.setData(taskAndAssessmentInfoVo);

        return ResultUtil.data(pp);
    }
/*
*  获取当前待办数量
* */
@GetMapping(value = "/get-performance-applying-tasks-num")
public Result  getPerformanceApplyingTasksNum(TaskQueryVo params, Query query) {
    List<String> departmentIds = new ArrayList<String>();
    try {
        departmentIds = feignInterface.getDepartmentIds();
    }catch (Exception e){
        e.printStackTrace();
        return ResultUtil.error(401,"登录超时");
    }
    if(departmentIds.size()==0){
        return ResultUtil.data(null);
    }
    Map mm=new HashMap();
    params.setUserOrgCodes(departmentIds);
    params.setUserCode(this.getLoginUser().getId());
    PagerModel<TaskVo> pm = flowableTaskService.getPerformanceApplyingTasks(params, query);
    System.out.println("num:"+pm.getData().size());
    mm.put("num",pm.getData().size() );
    return ResultUtil.data(mm);
}
    /*
     *  获取当前待办按日期分组
     * */
    @GetMapping(value = "/get-performance-applying-Group-by-day")
    public Result  getPerformanceApplyingGropByDay(TaskQueryVo params, Query query) {
        List<String> departmentIds = feignInterface.getDepartmentIds();
        if(departmentIds.size()==0){
            return ResultUtil.data(null);
        }
        Map mm=new HashMap();
        params.setUserOrgCodes(departmentIds);
        params.setUserCode(this.getLoginUser().getId());
        PagerModel<TaskVo> pm = flowableTaskService.getPerformanceApplyingTasks(params, query);
        LinkedHashSet<String> dateSet=new LinkedHashSet<>();
        List<String> proessId=new ArrayList<String>();
        SimpleDateFormat formate=new SimpleDateFormat("yyyy年MM月dd日");
        pm.getData().stream().forEach(taskVo -> {
            Date startTime = taskVo.getStartTime();
            dateSet.add(formate.format(startTime));
            proessId.add(taskVo.getProcessInstanceId());
        });
        Iterator<String> iterator = dateSet.iterator();
        List<Map<String,Object>> result=new ArrayList<>();
        List<Map<String, Object>> hkAssessmentScoreByProIds = feignPerformance.getHkAssessmentScoreByProIds(proessId);
        for(int i=0;i<hkAssessmentScoreByProIds.size();i++){
            String processInstanceId = hkAssessmentScoreByProIds.get(i).get("processInstanceId").toString();
            for(int j=0;j<pm.getData().size();j++){
                if(hkAssessmentScoreByProIds.get(i).get("processInstanceId").toString().equals(pm.getData().get(j).getProcessInstanceId())){
                    hkAssessmentScoreByProIds.get(i).put("date",formate.format(pm.getData().get(j).getStartTime()));
                }
            }

        }
        while (iterator.hasNext()){
            String next = iterator.next();
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("date",next+"绩效考核");
            HashSet<String> set=new HashSet<>();
            for(int i=0;i<hkAssessmentScoreByProIds.size();i++){

                if(hkAssessmentScoreByProIds.get(i).get("date")!=null&&next.equals(hkAssessmentScoreByProIds.get(i).get("date").toString())){
                    set.add(hkAssessmentScoreByProIds.get(i).get("hontUserId").toString());
                }
            }
            map.put("num",set.size()+"人参与");
            result.add(map);
        }

        return ResultUtil.data(result);
    }

    @GetMapping(value = "/get-performance-applying-detail")
    public Result  getPerformanceApplyingDetail(TaskQueryVo params, Query query) {
        List<String> departmentIds = new ArrayList<>();
        try {
            departmentIds = feignInterface.getDepartmentIds();
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(401,"登录超时请重新登录");
        }

        if(departmentIds.size()==0){
            Result<Object> data = ResultUtil.data(null);
            data.setMessage("0");
            return ResultUtil.data(null);
        }
        Map mm=new HashMap();
        params.setUserOrgCodes(departmentIds);
        params.setUserCode(this.getLoginUser().getId());
        PagerModel<TaskVo> pm = flowableTaskService.getPerformanceApplyingTasks(params, query);
        if(pm.getData().size()==0){
            Result<Object> data = ResultUtil.data(null);
            data.setMessage(0+"");
            return data;
        }

        List<String> proessId=new ArrayList<String>();
        SimpleDateFormat formate=new SimpleDateFormat("yyyy年MM月dd日");
        System.out.println("待办数量："+pm.getData().size());
        pm.getData().stream().forEach(taskVo -> {
            Date startTime = taskVo.getStartTime();
            proessId.add(taskVo.getProcessInstanceId());
        });

       // List<Map<String, Object>> hkAssessmentScoreByProIds = feignPerformance.getHkAssessmentScoreByProIds(proessId);
        List<PerformanceInfoNameAndUserNickVo> hkAssessmentInfoAndUserNickNameByProIds1 = feignPerformance.getHkAssessmentInfoAndUserNickNameByProIds(proessId);
        Iterator<PerformanceInfoNameAndUserNickVo> iterator1 = hkAssessmentInfoAndUserNickNameByProIds1.iterator();
        //过滤重复得数据
        List<String> empProcess=new ArrayList<String>();
        while (iterator1.hasNext()){
            PerformanceInfoNameAndUserNickVo next = iterator1.next();
            if(empProcess.contains(next.getProcessInstanceId())){
                iterator1.remove();
            }else{
                empProcess.add(next.getProcessInstanceId());
            }
        }
        LinkedHashMap<String,List<PerformanceInfoNameAndUserNickVo>> lingkmap=new LinkedHashMap<>();
        SimpleDateFormat formatemd=new SimpleDateFormat("MM月dd日");

        for(int i=0;i<hkAssessmentInfoAndUserNickNameByProIds1.size();i++){
            if(lingkmap.containsKey(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getCreateTime())){
                for(int j=0;j<pm.getData().size();j++){
                    if(pm.getData().get(j).getProcessInstanceId().equals(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getProcessInstanceId())){
                        hkAssessmentInfoAndUserNickNameByProIds1.get(i).setTaskId(pm.getData().get(j).getTaskId());
                        lingkmap.get(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getCreateTime()).add(hkAssessmentInfoAndUserNickNameByProIds1.get(i));
                        break;
                    }
                }

            }else{
                for(int j=0;j<pm.getData().size();j++){
                    if(pm.getData().get(j).getProcessInstanceId().equals(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getProcessInstanceId())){
                        List<PerformanceInfoNameAndUserNickVo> hkAssessmentInfoAndUserNickNameByProIds2 =new ArrayList<PerformanceInfoNameAndUserNickVo>();
                        hkAssessmentInfoAndUserNickNameByProIds1.get(i).setTaskId(pm.getData().get(j).getTaskId());
                        hkAssessmentInfoAndUserNickNameByProIds2.add(hkAssessmentInfoAndUserNickNameByProIds1.get(i));
                        lingkmap.put(hkAssessmentInfoAndUserNickNameByProIds1.get(i).getCreateTime(),hkAssessmentInfoAndUserNickNameByProIds2);
                        break;
                    }
                }
            }
        }


       // List<PerformanceInfoNameAndUserNickVo> hkAssessmentInfoAndUserNickNameByProIds = feignPerformance.getHkAssessmentInfoAndUserNickNameByProIds(proessId);
        Result<LinkedHashMap<String, List<PerformanceInfoNameAndUserNickVo>>> data = ResultUtil.data(lingkmap);

        data.setMessage(pm.getData().size()+"");
        return data;
    }
/*
* 获取待办的list 列表
* */
@GetMapping(value = "/get-list-applyed-tasks")
public String getListApplyedTasks(String date) {
    List<String> list=new ArrayList<String>();
    TaskQueryVo params=new TaskQueryVo();
    Query query=new Query();
    List<String> departmentIds = feignInterface.getDepartmentIds();
    if(departmentIds.size()==0){
        return null;
    }
    Map mm=new HashMap();
    params.setUserOrgCodes(departmentIds);
    params.setUserCode(this.getLoginUser().getId());
    PagerModel<TaskVo> pm = flowableTaskService.getPerformanceApplyingTasks(params, query);
    StringBuffer buffer=new StringBuffer();
    pm.getData().stream().forEach(taskVo -> {
        buffer.append(taskVo.getProcessInstanceId()+":"+taskVo.getTaskId()+",");
    });
    System.out.println("buffer:"+buffer.toString());
    return buffer.toString();
}
    /**
     * 获取已办任务列表
     *
     * @param params 参数
     * @param query  查询条件
     * @return
     */
    @GetMapping(value = "/get-applyed-tasks")
    public PagerModel<TaskVo> getApplyedTasks(TaskQueryVo params, Query query) {
        params.setUserCode(this.getLoginUser().getId());
        PagerModel<TaskVo> pm = flowableTaskService.getApplyedTasks(params, query);
        return pm;
    }

    /**
     * 获取已办任务列表
     *
     * @param params 参数
     * @param query  查询条件
     * @return
     */
    @GetMapping(value = "/my-processInstances")
    public PagerModel<ProcessInstanceVo> myProcessInstances(ProcessInstanceQueryVo params, Query query) {
        params.setUserCode(this.getLoginUser().getId());
        PagerModel<ProcessInstanceVo> pm = flowableProcessInstanceService.getMyProcessInstances(params, query);
        return pm;
    }



    /**
     * 查询表单详情
     * @param params 参数
     * @return
     */
    @PostMapping(value = "/find-formInfo")
    public ReturnVo<FormInfoVo> findFormInfoByFormInfoQueryVo(FormInfoQueryVo params) throws Exception{
        ReturnVo<FormInfoVo> returnVo = new ReturnVo<>(ReturnCode.SUCCESS,"OK");
        FormInfoVo<Leave> formInfoVo = new FormInfoVo(params.getTaskId(),params.getProcessInstanceId());
        String processInstanceId = params.getProcessInstanceId();
        String businessKey = null;
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if (processInstance == null){
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            businessKey = historicProcessInstance.getBusinessKey();
        }else {
            businessKey = processInstance.getBusinessKey();
        }
        Leave leave = leaveService.getLeaveById(businessKey);
        formInfoVo.setFormInfo(leave);
        returnVo.setData(formInfoVo);
        return returnVo;
    }
   /*
   * 根据实例id 列表查询个实例所在节点
   * */
   @PostMapping(value = "/getRunProcessInstanceNodeNameByPids")
   public Result getRunProcessInstanceNodeNameByPids(String ids){
       List<ProcessNodeNameAndProcessInstanceIdVo> vos=  flowableTaskService.getRunProcessInstanceNodeNameByPids(ids);
       return ResultUtil.data(vos);
   }
}
